import os
import time

from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt, QThread, QMutex, QWaitCondition
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtCore import QTimer, QDateTime
from d435 import D435
from ultralytics import YOLO
from arm import Rokae
import json
from task import Task
from grab_win import GrabWindow
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
from lift import Lift


class Controller:
    def __init__(self, win: GrabWindow, camera_detection: D435, robotArm: Rokae, model: YOLO, lift:Lift):
        self.win = win
        self.cam = camera_detection
        self.arm = robotArm
        self.model = model
        self.lift = lift
        self.color_image = None
        self.depth_image = None
        self.timer = QTimer(win)
        self.timer.timeout.connect(self.onTimer)
        self.timer.start(1000)  # 设置定时器每1000毫秒（1秒）触发一次
        # task
        self.win.ui.pushButtonEditTask.clicked.connect(self.onButtonEditTask)
        self.win.ui.pushButtonRunTask.clicked.connect(self.onButtonRunTask)
        self.win.ui.pushButtonLoadTask.clicked.connect(self.onButtonLoadTask)
        self.win.ui.pushButtonPauseTask.clicked.connect(self.onButtonPauseTask)
        self.win.ui.pushButtonResumeTask.clicked.connect(self.onButtonResumeTask)
        self.win.ui.pushButtonStopTask.clicked.connect(self.onButtonStopTask)
        self.win.ui.pushButtonAGVSetting.clicked.connect(self.onButtonAGVSetting)

        # tool
        self.win.ui.pushButtonToolClose.clicked.connect(self.onButtonToolClose)
        self.win.ui.pushButtonToolOpen.clicked.connect(self.onButtonToolOpen)

        self.task = None
        self.taskConfig = None

    def onButtonAGVSetting(self):
        # self.win.ui.lineEditAGVIP.get
        QDesktopServices.openUrl(QUrl("http://192.168.100.100:8080"))

    def onButtonPauseTask(self):
        if self.task is not None and self.task.is_paused == False:
            self.task.pause()
        pass

    def onButtonResumeTask(self):
        if self.task is not None and self.task.is_paused == True:
            self.task.resume()
        pass

    def onButtonToolClose(self):
        self.arm.setEndClose()

    def onButtonToolOpen(self):
        self.arm.setEndOpen()

    def onTimer(self):
        if self.task is None:
            self.cam.update()
            self.color_image, self.depth_image = self.cam.get_images()
            self.update_image(self.color_image)
        else:
            if self.task.num > 1:
                self.update_image(self.task.result_image)


    def convert_cv_qt(self, img):
        """将 OpenCV 图像转换为 QImage"""
        if len(img.shape) == 2:  # 灰度图
            height, width = img.shape
            bytes_per_line = width
            qimg = QImage(img.data, width, height, bytes_per_line, QImage.Format_Grayscale8)
        else:  # 彩色图
            height, width, channel = img.shape
            bytes_per_line = 3 * width
            qimg = QImage(img.data, width, height, bytes_per_line, QImage.Format_RGB888).rgbSwapped()
        return qimg

    def update_image(self,image):
        """更新 QLabel 上显示的图像"""
        qimg = self.convert_cv_qt(image)
        pixmap = QPixmap.fromImage(qimg)
        self.win.ui.ImageQlabel.setPixmap(pixmap)
        self.win.ui.ImageQlabel.setAlignment(Qt.AlignCenter)

    def onButtonLoadTask(self):
        if self.task is not None:
            self.win.ui.textBrowserStatus.append("请先停止任务")
            return

        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.ExistingFiles)
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptOpen)
        # file_path, _ = dialog.getOpenFileName(None, "选择文件", "C:/", "json文件(*.json)")
        self.Path = os.getcwd()
        dialog.exec_()
        openfile_name = dialog.selectedFiles()
        print(openfile_name[0])
        if len(openfile_name) != 0:
            with open(openfile_name[0], 'r+', encoding='utf-8') as f:
                self.taskConfig = json.load(f)
                print(self.taskConfig)
                self.task = Task(self.taskConfig, self.arm, self.cam,self.model, self.lift, self)
                self.win.ui.textBrowserStatus.append("载入任务成功")

    def onButtonRunTask(self):
        if  self.taskConfig is not None and self.task is not None:
            self.task.start()

    def onButtonStopTask(self):
        if  self.taskConfig is not None and self.task is not None:
            self.task.stop()
            time.sleep(2)
            self.task = None

    def onButtonEditTask(self):
        print("d")
        # file_path, _ = QFileDialog.getOpenFileName(self, "选择文件", "C:/", "json文件(*.json)")
        #
        # if file_path:
        #     print("选择的目录路径：", file_path)
    def onInfo(self, info:str):

        scroll_bar = self.win.ui.textBrowserStatus.verticalScrollBar()
        scroll_bar.setValue(scroll_bar.maximum())
        self.win.ui.textBrowserStatus.append(info)
